package com.template.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class TemplateService extends Service {
    private static TemplateService.TemplateAidlInterfaceImpl mBinder;
    private String TAG = "TemplateService";
    private boolean serviceRunning = false;
    private String mData = "默认消息";
    private Map<String, TemplateServiceCallBack> mClientListenerMap =
            new HashMap<String, TemplateServiceCallBack>();

    // 返回Binder对象
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return mBinder;
    }

    // 创建Service时调用该方法，只调用一次
    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
        if (null == mBinder){
            initService();
        }
        serviceRunning = true;
        startTestData();
    }

    // 每次启动Service时都会调用该方法
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        if (null == mBinder){
            initService();
        }
        mData = intent.getStringExtra("data");
        return START_STICKY;
    }

    // 解绑Service调用该方法
    @Override
     public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    // 退出或者销毁时调用该方法
    @Override
    public void onDestroy() {
        serviceRunning = false;
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

    //实现AIDL的接口
    private class TemplateAidlInterfaceImpl extends TemplateAidlInterface.Stub{
        @Override
        public void setData(String data) throws RemoteException {
            Log.i(TAG, "dataChange");
            mData = data;
        }

        @Override
        public synchronized void registerCallback(String clientId, TemplateServiceCallBack callback) throws RemoteException {
            mClientListenerMap.put(clientId, callback);
        }

        @Override
        public synchronized void unRegisterCallback(String clientId, TemplateServiceCallBack callback) throws RemoteException {
            mClientListenerMap.remove(clientId);
        }
    }

    //初始化服务，主要是向系统注册服务
    private void initService(){
        if (null == mBinder){
            synchronized (TemplateService.class) {
                if (null == mBinder){
                    try {
                        mBinder = new TemplateService.TemplateAidlInterfaceImpl();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void startTestData() {
        new Thread() {
            @Override
            public void run() {
                int n = 0;
                while (serviceRunning) {
                    n++;
                    String str = n + mData;
                    Log.d(TAG, "dsa: " + str);
                    try {
                        onDataChange(str);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }

    // 通知到client
    private synchronized void onDataChange(String data) throws RemoteException {
        for (Iterator i = mClientListenerMap.values().iterator(); i.hasNext(); ) {
            Object obj = i.next();
            if (obj instanceof TemplateServiceCallBack) {
                TemplateServiceCallBack callBack = (TemplateServiceCallBack) obj;
                if (callBack != null) {
                    callBack.onDataChanged(data);
                }
            }
        }
    }
}